import { defineComponent, onMounted, onUpdated,provide } from "vue";
import "../styles/scrollbar.scss";
import Bar from "./bar";
import {ref} from 'vue'
import {GAP,scrollbarContextKey} from "./constants"
export default defineComponent({
  setup(_, { slots }) {
    let scrollbarRef = ref<HTMLDivElement>()//整个视图的高度包括内容和滚动条
    let scrollRef = ref<HTMLDivElement>()// 内容盒子  
      // 获取子组件的ref
    let barRef = ref()

    let ratioY = ref(1)
    let ratioX = ref(1)

    let sizeHeight = ref(0)
    let sizeWidth = ref(0)
      // 滚动事件
    let handleScroll = ()=>{
      if(scrollRef.value){
         barRef.value?.handleScroll(scrollRef.value)
      }
    }

    // 初始宽高度值
    const update = ()=>{
        if(scrollRef.value){
            // offsetHeight即是自身的高度
            const offsetHeight = scrollRef.value?.offsetHeight -GAP
            // offsetHeight即是自身的宽度
            const offsetWidth = scrollRef.value?.offsetWidth - GAP
            // 原始的高度~~~~scrollHeight是整个容器的高度
            const originalHeight = offsetHeight ** 2 / scrollRef.value.scrollHeight
            //原始的宽度
            const originalWidth = offsetWidth ** 2 / scrollRef.value.scrollWidth
            const height = Math.max(originalHeight,20)
             const width = Math.max(originalWidth,20)

            //  移动的距离比例
            ratioY.value = originalHeight/
            (offsetHeight-originalHeight)/
            (height/(offsetHeight-height))

            ratioX.value = originalWidth/
            (offsetWidth-originalWidth)/
            (width/(offsetWidth-width))

            // 滚动条的高度
            sizeHeight.value =height +GAP <offsetHeight?height:0

            // 滚动条的宽度
            sizeWidth.value = width +GAP<offsetWidth?width:0


        }else{
            return
        }
    }

    onUpdated(()=>{
        update()
    })

    onMounted(()=>{
        update()
    })

    //给子组件传自己的组件
    provide(scrollbarContextKey,{
      scrollbarElement:scrollbarRef as unknown as HTMLDivElement,
      wrapElement:scrollRef as unknown as HTMLDivElement,
    })

    return () => (
      <>
        <div ref={scrollbarRef} class={"hid"}>
          <div ref={scrollRef} class={"scrollbar__wrap"} onScroll={()=>handleScroll()}>
            <div>{slots.default?.()}</div>
          </div>
          <div>
            <Bar ref={barRef} ratio-x={ratioX.value} ratio-y={ratioY.value} 
            height={sizeHeight.value} width={sizeWidth.value}></Bar>
          </div>
        </div>
      </>
    );
  },
});
